package org.lanqiao.controller.login;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.lanqiao.config.entity.ResponseData;
import org.lanqiao.login.IAdminService;
import org.lanqiao.users.Admin;
import org.lanqiao.utils.JWTUtil;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/user/login")
@Api(tags = "用户/管理员操作user接口")
public class AdminController {
    @Reference
    private IAdminService adminService;
//    @Reference
//    HttpServletRequest request;

    @GetMapping("/login")
    @ApiOperation(value = "登陆接口",notes = "用户名和密码认证")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "账号",paramType ="query",required = true,name = "loginname",dataType = "String"),
            @ApiImplicitParam(value = "密码",paramType ="query",required = true,name = "pass",dataType = "String")
    })
    public ResponseData<Admin> login(@RequestParam String loginname, @RequestParam String pass, HttpSession session){
        System.out.println(loginname+"++++++++++++++"+pass);
//        Admin admin = adminService.queryAdminByNameAndPwd(loginname,pass);
//        ResponseData responseData = ResponseData.success();
//        if(admin != null){
//            String token = JWTUtil.generToken(admin.getId().toString(),"LiuLiu@Mall",admin.getName());
//            //向浏览器返回token
//            responseData.putDataVule("token",token);
//            //返回用户信息
//            responseData.putDataVule("admin",admin);
//        }else {
//            responseData = ResponseData.cusstomerError("用户名或密码错误");
//        }

        ResponseData responseData = null;
        //根据用户名查询用户信息
        Admin admin = adminService.queryAdminByNameAndPwd(loginname,"1");
        if(admin == null){
            responseData = ResponseData.cusstomerError("用户不存在");
        }else{
            boolean checkPw =  BCrypt.checkpw(pass,admin.getPass());
            if(checkPw){
                String token =  JWTUtil.generToken(admin.getId().toString(),"LiuLiu@Mall",admin.getName());
                responseData = ResponseData.success().putDataVule("token",token).putDataVule("admin",admin);
                //Session
                //HttpServletRequest request = null;
                //HttpSession session  = request.getSession(true);
//                HttpSession session = request.getSession(true);
                session.setAttribute("id",admin.getId());
                System.out.println(session.getAttribute("id"));
                responseData = ResponseData.success().putDataVule("token",token).putDataVule("admin",admin).putDataVule("session",session);
            }else{
                responseData = ResponseData.cusstomerError("用户认证失败");
            }
        }
        return responseData;
    }



    //待完善


    //@ApiImplicitParam(value = "个人信息", name = "admin", required = true, paramType = "query", dataTypeClass = Admin.class)
    public ResponseData<Admin> updata(@RequestBody Admin admin){
        try{
            adminService.upuserdata(admin);
            return ResponseData.success();
        } catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

    //用户注册

    @GetMapping("/add")
    @ApiOperation(value = "注册接口",notes = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "账号",paramType ="query",required = true,name = "loginname",dataType = "String"),
            @ApiImplicitParam(value = "密码",paramType ="query",required = true,name = "pass",dataType = "String")
    })

    public ResponseData<Admin> add(@RequestParam String loginname,@RequestParam String pass){
        boolean che =check(loginname);
        if (che == true) {
            try {
                Admin admin = new Admin();
                admin.setName(loginname);
                //获取烟
                String salt = BCrypt.gensalt();//29个字符  随机生成
                System.out.println(salt);
                String newpass = BCrypt.hashpw(pass, salt);
                admin.setPass(newpass);
                //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                admin.setRegDate(new Date());
                admin.setStatus(0);
                admin.setCollectCount(0);
                admin.setCreateCount(0);
                admin.setAskCount(0);
                admin.setAnsCount(0);
                admin.setUserLevel(1);
                admin.setLoginDate("0天");
                adminService.addadmin(admin);
                return ResponseData.success();
            } catch (Exception e) {
                return ResponseData.serverInternalError();
            }
        }else {
            return ResponseData.cusstomerError("用户名已存在！");
        }
    }



    //密码的修改
    @GetMapping("/updatapass")
    @ApiOperation(value = "改密接口",notes = "用户改密")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
            @ApiImplicitParam(value = "密码",paramType ="query",required = true,name = "pass",dataType = "String")
    })

    public ResponseData<Admin> uptepass(@RequestParam Integer id,@RequestParam String pass){
        if (pass == null){
            return ResponseData.cusstomerError("密码不能为空！");
        }else {
            try {
                Admin admin = adminService.selectid(id);
                //获取烟
                String salt = BCrypt.gensalt();//29个字符  随机生成
                System.out.println(salt);
                String newpass = BCrypt.hashpw(pass, salt);
                admin.setPass(newpass);
                updata(admin);
                return ResponseData.success();
            } catch (Exception e) {
                return ResponseData.serverInternalError();
            }
        }
    }


    //管理员对用户删除（根据用户名）
    @GetMapping("/delete")
    @ApiOperation(value = "删除用户接口",notes = "用户删除")
    @ApiImplicitParam(value = "账号",paramType ="query",required = true,name = "loginname",dataType = "String")
    public ResponseData<Admin> deleteuser(@RequestParam String loginname){
        try{
            adminService.deleteuser(loginname);
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

    public boolean check(String loginname){

        Admin admin = adminService.selectloginname(loginname);
        if (admin == null){
            return true;
        }else
        return false;
    }

    @GetMapping("/adminPage")
    @ApiOperation(value = "分页查询",notes = "分页查询所有用户品牌信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页数",name = "pagenum",required = false,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value = "每页条数",name = "pagesize",required = false,dataType = "Integer",paramType = "query")
    })

    public ResponseData<Admin> searchpage(@RequestParam  Integer pagenum,@RequestParam Integer pagesize){
        IPage<Admin> sepage =  adminService.searchPage(pagenum,pagesize);
        return ResponseData.success().putDataVule("total",sepage.getTotal())
                .putDataVule("pages",sepage.getPages())
                .putDataVule("adminList",sepage.getRecords());
    }

    @PostMapping("/brandPage")
    @ApiOperation(value = "分页条件查询",notes = "根据条件分页查询品牌信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页数",name = "pagenum",required = false,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value = "每页条数",name = "pagesize",required = false,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value = "查询条件",name = "queryMap",required = false,dataType = "Map",paramType = "body")
    })
    public ResponseData<Admin> searchByCondition(@RequestParam Integer pagenum, @RequestParam Integer pagesize, @RequestBody Map<String,Object> queryMap){
        IPage<Admin> adminPage =  adminService.searchByCondition(pagenum,pagesize,queryMap);
        return ResponseData.success().putDataVule("total",adminPage.getTotal())
                .putDataVule("pages",adminPage.getPages())
                .putDataVule("brandList",adminPage.getRecords());
}


    @GetMapping("/changestatus")
    @ApiOperation(value = "更改status接口", notes = "填写数值")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
            @ApiImplicitParam(value = "status",paramType ="query",required = true,name = "status",dataType = "Integer")
    })
    public ResponseData<Admin> changestatus(@RequestParam Integer id,@RequestParam Integer status){
        try{
            Admin admin= adminService.selectid(id);
            System.out.println(admin.getName());
            admin.setStatus(status);
            updata(admin);
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

    @GetMapping("/changeoneselfmessage")
    @ApiOperation(value = "填写个人信息接口", notes = "完善信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
            @ApiImplicitParam(value = "电话",paramType ="query",required = true,name = "phone",dataType = "String"),
            @ApiImplicitParam(value = "性别",paramType ="query",required = true,name = "sex",dataType = "String"),
            @ApiImplicitParam(value = "头像",paramType ="query",required = true,name = "head",dataType = "String")
    })
    public ResponseData<Admin> addmessage(@RequestParam Integer id,@RequestParam String phone,@RequestParam String sex,@RequestParam String head){
        try{
            Admin admin= adminService.selectid(id);
            System.out.println(admin.getName());
            admin.setUserPhone(phone);
            admin.setUserSex(sex);
            admin.setUserHead(head);
            updata(admin);
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

    @GetMapping("/logindate")
    @ApiOperation(value = "账号存在时间接口", notes = "已使用时间")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer")
    })
    //更新登陆时间
    public ResponseData<Admin> logindate(@RequestParam Integer id){
        try{
            Admin admin= adminService.selectid(id);
            Date date1 = admin.getRegDate();
            Date date2 = new Date();
            int year = (int) ((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24)) / 365; // 计算年
            int day = (int) ((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24)); // 计算天
            String dates =year + "年，" + "总共" + day + "天。";
            System.out.println(dates+"-----------------------------------------");
            admin.setLoginDate(dates);
            updata(admin);
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }

    }

    @GetMapping("/updateLevel")
    @ApiOperation(value = "等级更新", notes = "等级更新")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer")
    })

    public ResponseData<Admin> updatalevel(@RequestParam Integer id){
        try{
            Admin admin= adminService.selectid(id);
            Integer a = admin.getLikedCount();
            System.out.println(a+"+++++++++++++++++++++++++++++++++++++++++++++++++++++");
            if (a >= 500){
                admin.setUserLevel(2);
                updata(admin);
            }else if (a > 1000){
                admin.setUserLevel(3);
                updata(admin);
            }else {
                admin.setUserLevel(1);
                updata(admin);
            }
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

    @GetMapping("/updatalike")
    @ApiOperation(value = "更新被点赞数", notes = "填写数值")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
            @ApiImplicitParam(value = "被点赞数",paramType ="query",required = true,name = "likedCount",dataType = "Integer")
    })
    public ResponseData<Admin> updatalike(@RequestParam Integer id,@RequestParam Integer likedCount) {
        try {
            Admin admin = adminService.selectid(id);
            System.out.println(admin.getName());
            admin.setStatus(likedCount);
            updata(admin);
            return ResponseData.success();
        } catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

        @GetMapping("/updatacreat")
        @ApiOperation(value = "分享资源数更改", notes = "填写id")
        @ApiImplicitParams({
                @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
                @ApiImplicitParam(value = "指令值(0增加/1删除)",paramType ="query",required = true,name = "num",dataType = "Integer")
        })
        public ResponseData<Admin> updatacreat(@RequestParam Integer id,@RequestParam Integer num){
            try{
                Admin admin= adminService.selectid(id);
                Integer a =admin.getCreateCount();
                if(num == 0) {
                    a++;
                }else if (num== 1){
                    a--;
                }
                admin.setCreateCount(a);
                updata(admin);
                return ResponseData.success();
            }catch (Exception e) {
                return ResponseData.serverInternalError();
            }
    }

    ////////////////////////////////////////////////////////////////////////////////////

    @GetMapping("/updataask")
    @ApiOperation(value = "发布求助数更改", notes = "填写id")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
            @ApiImplicitParam(value = "指令值(0增加/1删除)",paramType ="query",required = true,name = "num",dataType = "Integer")
    })
    public ResponseData<Admin> updataask(@RequestParam Integer id,@RequestParam Integer num){
        try{
            Admin admin= adminService.selectid(id);
            Integer a =admin.getAskCount();
            if(num == 0) {
                a++;
            }else if (num== 1){
                a--;
            }
            admin.setAskCount(a);
            updata(admin);
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////

    @GetMapping("/updataans")
    @ApiOperation(value = "回答数更改", notes = "填写id")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
            @ApiImplicitParam(value = "指令值(0增加/1删除)",paramType ="query",required = true,name = "num",dataType = "Integer")
    })
    public ResponseData<Admin> updataans(@RequestParam Integer id,@RequestParam Integer num){
        try{
            Admin admin= adminService.selectid(id);
            Integer a =admin.getAnsCount();
            if(num == 0) {
                a++;
            }else if (num== 1){
                a--;
            }
            admin.setAnsCount(a);
            updata(admin);
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////

    @GetMapping("/updatacollect")
    @ApiOperation(value = "收藏数更改", notes = "填写id")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = true,name = "id",dataType = "Integer"),
            @ApiImplicitParam(value = "指令值(0增加/1删除)",paramType ="query",required = true,name = "num",dataType = "Integer")
    })
    public ResponseData<Admin> updatacollect(@RequestParam Integer id,@RequestParam Integer num){
        try{
            Admin admin= adminService.selectid(id);
            Integer a =admin.getCollectCount();
            if(num == 0) {
                a++;
            }else if (num== 1){
                a--;
            }
            admin.setCollectCount(a);
            updata(admin);
            return ResponseData.success();
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }

    ////////////////////////////////////
    @GetMapping("/selectid")
    @ApiOperation(value = "根据id查询用户信息", notes = "填写id")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id",paramType ="query",required = false,name = "id",dataType = "Integer"),

    })
    public ResponseData<Admin> selectid(@RequestParam Integer id){
        try{
            Admin admin= adminService.selectid(id);
            return ResponseData.success().putDataVule("admin",admin);
        }catch (Exception e) {
            return ResponseData.serverInternalError();
        }
    }





}
